package auth

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	AdminModel "jy_go/app/admin/model/admin"
	"jy_go/app/admin/model/power"
	"jy_go/app/admin/model/role_power"
	Config "jy_go/config"
	"jy_go/db"
	JWT "jy_go/jwt"
	"net/http"
	"net/url"
)

var (
	Db    = db.GetDb()
	admin AdminModel.Admin

)

//token验证
func RolePowerVerification()gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		id, err := JWT.AnalysisToken(token,[]byte(Config.Config("config","jwt","admin_jwt_key")))
		if err != nil {
			c.JSON(http.StatusUnauthorized,gin.H{"message":err.Error()})
			c.Abort()
			return
		}

		if err := Db.Take(&admin).Error; err != nil {
			if errors.Is(err,gorm.ErrRecordNotFound) {
				c.JSON(http.StatusUnauthorized,gin.H{"message":"登录失效，请重新登录"})
				c.Abort()
				return
			}
		}

		if admin.Type != 1 {
			c.JSON(http.StatusUnauthorized,gin.H{"message":"该账号已被禁用"})
			c.Abort()
			return
		}

		if err := AdminRolePower(admin.RoleId,c.Request.URL); err != nil {
			c.JSON(http.StatusUnauthorized,gin.H{"message":err.Error()})
			c.Abort()
			return
		}
		c.Set("AdminId", id)
		c.Next()
	}
}


/**
角色权限
**/
func AdminRolePower(RoleId int ,Url *url.URL) error {

	 err := Db.Model(&power.Power{}).
	 	Select("p.id").
	 	Joins("as p JOIN jy_role_power as r on r.power_id = p.id").
	 	Where("r.role_id = ? AND p.url = ?",RoleId,Url.Path).
	 	Take(&role_power.RolePower{}).Error

	if err != nil || errors.Is(err,gorm.ErrRecordNotFound) {
		return errors.New("你无此权限")
	}
	return nil
}









